#include "GLSLShader.h"
#include <QByteArray>

#include <iostream>

using namespace PBVP;

GLSLShader::GLSLShader(const QString& fname, GLenum type)
{
	m_shaderType = type;
	m_isValid = false;
	m_shaderId = glCreateShader(m_shaderType);
	if (m_shaderId == 0)	// Error, return as invalid
	{
#ifdef _DEBUG
		std::cerr << "Cannot create shader object\n";
#endif
		return;
	}
	if(!loadShader(fname)) {
#ifdef _DEBUG
		std::cerr<< "Cannot load shader file " << fname.toStdString() << std::endl;
#endif
		return;
	}
	// now change the valid flag to true
	m_isValid = true;
}

GLSLShader::~GLSLShader(void)
{
	if (isValid())
	{
		glDeleteShader(m_shaderId);
	}
}

bool GLSLShader::loadShader(const QString& fname)
{
	QFile file(fname);
	if (!file.open(QIODevice::ReadOnly))
	{
		return false;
	}
	QByteArray bytes = file.readAll();
	// Load source code into shaders
	char *data = bytes.data();
	glShaderSource(m_shaderId, 1, (const char **)&data, 0);
	file.close();

	// Compile the shader and print out the log file
	glCompileShader(m_shaderId);
	GLint status;
	glGetShaderiv(m_shaderId, GL_COMPILE_STATUS, &status);
	if(status == GL_TRUE) return true;
	return false;
}